package com.ydd.controller.amidn;

import com.ydd.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.ydd.config.MvcConfig.UPLOAD_IMAGE_PATH;

@RestController
@RequestMapping("/common")
@Slf4j
public class FileController {

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        if (!file.isEmpty()) {
            try {
                String savePath = "/upload/" + UUID.randomUUID().toString() + "-" + file.getOriginalFilename();

                // 保存文件到本地磁盘
                File destFile = new File("D:/tp/", file.getOriginalFilename());
                file.transferTo(destFile);

                // 构建返回前端的 URL 地址
                String baseUrl = request.getRequestURL().toString().replace(request.getRequestURI(), "");
                String url = baseUrl + savePath;

                // 返回成功的响应结果
                Map<String, Object> data = new HashMap<>();
                data.put("mime", file.getContentType());
                data.put("name", file.getOriginalFilename());
                data.put("size", file.getSize());
                data.put("savePath", url);

                result.put("errno", 0);
                result.put("errmsg", "");
                result.put("data", data);

            } catch (Exception ex) {
                // 处理上传过程中发生的异常
                result.put("errno", -1);
                result.put("errmsg", "上传失败：" + ex.getMessage());
                result.put("data", new HashMap<>());
            }
        } else {
            result.put("errno", -1);
            result.put("errmsg", "没有选择文件上传");
            result.put("data", new HashMap<>());
        }

        return result;
    }

}
